package com.jungle.bfi.controller;

import com.jungle.base.dao.SpecBuilder;
import com.jungle.base.domain.bo.BaseUserBo;
import com.jungle.base.domain.vo.JsonResult;
import com.jungle.bfi.domain.bo.DataDefinitionBo;
import com.jungle.bfi.domain.vo.DataDefinitionVo;
import com.jungle.bfi.entity.DataCategoryPo;
import com.jungle.bfi.entity.DataDefinitionPo;
import com.jungle.bfi.service.metadata.DataCategoryService;
import com.jungle.bfi.service.metadata.DataDefinitionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("dataDefinition")
public class DataDefinitionController {
    @Resource
    private DataDefinitionService dataDefinitionService;
    @Resource
    private DataCategoryService dataCategoryService;

    @PostMapping("store")
    public JsonResult<DataDefinitionVo> store(@RequestBody DataDefinitionBo qo) {
        DataDefinitionPo dataDefinitionPo = dataDefinitionService.saveOrUpdate(qo, new BaseUserBo());
        DataDefinitionVo vo = new DataDefinitionVo();
        BeanUtils.copyProperties(dataDefinitionPo, vo);
        DataCategoryPo categoryPo = dataCategoryService.findByCode(dataDefinitionPo.getCategoryValue());
        if (categoryPo != null) {
            vo.setCategoryName(categoryPo.getName());
        }

        return JsonResult.success(vo);
    }

    @PostMapping("list")
    public JsonResult<List<DataDefinitionVo>> findAll(@RequestBody DataDefinitionBo bo) {
        List<DataDefinitionPo> poList = dataDefinitionService.findAll(new SpecBuilder<DataDefinitionPo>(bo).toSpec());
        List<DataCategoryPo> categoryPoList = dataCategoryService.findAll(null);
        List<DataDefinitionVo> voList = poList.stream().map(po -> {
            DataDefinitionVo vo = new DataDefinitionVo();
            BeanUtils.copyProperties(po, vo);
            // 绑定分类名称
            categoryPoList.stream()
                    .filter(category -> Objects.equals(po.getCategoryValue(), category.getCode())).findAny()
                    .ifPresent(category -> vo.setCategoryName(category.getName()));
            return vo;
        }).toList();
        return JsonResult.success(voList);
    }

    @PostMapping("bizBillTypeList")
    public JsonResult<List<DataDefinitionVo>> scenarioList(@RequestBody DataDefinitionBo bo) {
        List<DataDefinitionVo> list = dataDefinitionService.scenarioList(bo);
        return JsonResult.success(list);
    }
}
